<?php

include_once dirname(__FILE__) . '/../system/settings.php';
if ($_POST) {
    $id = $_POST['id'];
    $type = $_POST['type'];
    if ($_POST['id_enterprise']) {
        $id_enterprise = $_POST['id_enterprise'];
    } else {
        $id_enterprise = NULL;
    }
    
    
    
    $d = explode("/",$_POST['expiration']);
    
    $href = $_POST['href'];
    $target = $_POST['target'];
    $title = $_POST['title'];
    
    $expiration = $d[2]."-".$d[1]."-".$d[0];
    

    if ($_FILES['filepicture']) {
        /* upload de arquivo */
        $arquivo = $_FILES['filepicture'];
        $ext = pathinfo($arquivo['name'], PATHINFO_EXTENSION);
        $filepicture = md5(uniqid(time())) . '.' . $ext;
        $caminho_arquivo_servidor = __IMG_DIR__ . 'banner/' . $filepicture;
        if ($ext == 'jpg' or $ext == 'gif' or $ext == 'png' or $ext == 'swf') {
            if (move_uploaded_file($arquivo['tmp_name'], $caminho_arquivo_servidor)) {
                if ($ext == 'jpg' or $ext == 'png') {
                    $img = new Canvas();
                    $img->carrega($caminho_arquivo_servidor);
                    switch ($type) {
                        case 1: $img->redimensiona('752', '92', 'crop');
                            break;
                        case 2: $img->redimensiona('370', '264', 'crop');
                            break;
                        case 3: $img->redimensiona('300', '100', 'crop');
                            break;
                        case 4: $img->redimensiona('180', '50', 'crop');
                            break;
                        case 5: $img->redimensiona('627', '100', 'crop');
                            break;
                        case 6: $img->redimensiona('120', '60', 'crop');
                            break;
                        case 7: $img->redimensiona('220', '122', 'crop');
                            break;
                    }
                    $img->grava($caminho_arquivo_servidor, 100);
                }
            }
        }

        if (!empty($id)) {
            if (!BannersControl::Update($type, $filepicture, $id_enterprise, $href, $target, $title,$expiration, $id)) {
                header("location: " . $_POST['redirect']);
                exit();
            }
        } else {
            if (!BannersControl::Insert($type, $filepicture, $id_enterprise, $href, $target, $title,$expiration)) {
                header("location: " . $_POST['redirect']);
                exit();
            }
        }
    }
    header("location: " . $_POST['redirect']);
} else if ($_GET) {
    $id = $_GET['id'];
    $caminho_arquivo_servidor = __IMG_DIR__ . 'banner/';
    $data = BannersControl::Select($id);
    if (!empty($id)) {
        unlink($caminho_arquivo_servidor.$data[0]['filepicture']);
        BannersControl::Delete($id);
    }
    header("location: " . $_GET['redirect']);
}
?>
